<template>
  <div class="book">
    <div>
      <span>图书名称:</span>
      <input
        type="text"
        v-model="newName"
        @input="isNotPost"
        ref="myInp"
        value="newName"
      />
    </div>
    <div>
      <button :disabled="flag" @click="onAdd">添加/修改</button>
    </div>
    <table border="1" cellpadding="10" cellspacing="0">
      <tr>
        <th>序号</th>
        <th>图书名称</th>
        <th>创建时间</th>
        <th>操作</th>
      </tr>
      <tr v-for="item in books" :key="item.id">
        <td>{{ item.id }}</td>
        <td>{{ item.name }}</td>
        <td>{{ item.date | newdate }}</td>
        <td>
          <button @click="onDle(item.id)">删除</button>
          <button @click="revise(item.id)">编辑</button>
        </td>
      </tr>
    </table>
  </div>
</template>

<script>
import axios from 'axios'
axios.defaults.baseURL = ' http://liufusong.top:4000/'
export default {
  props: ['books'],
  data () {
    return {
      allId: [],
      nName: [],
      newName: [],
      newDate: '',
      newId: '',
      flag: false
    }
  },

  created () {},

  methods: {
    isNotPost (newName) {
      // axios({
      //   url: 'books/book/' + this.newName,
      //   method: 'GET'
      // }).then((res) => {
      //   console.log(res.status)
      //   this.flag = (res.status === 1)
      // })
      // 遍历把name值都拿出来
      this.books.forEach(item => this.nName.push(item.name))
      this.flag = this.nName.includes(this.newName.trim())
      console.log(this.flag)
    },
    onAdd (newName, newId, flag) {
      this.books.forEach(item => this.allId.push(item.id))
      // id数组内不重复->添加
      if (!this.allId.includes(this.newId)) {
        axios({
          url: 'books',
          method: 'POST',
          data: { name: this.newName }
        }).then((res) => {
          console.log(res.status)
        })
      } else {
        // id数组内重复->进行修改
        console.log('进行修改')
        axios({
          url: 'books/' + this.newId,
          method: 'PUT',
          data: { name: this.newName }
        }).then((res) => {
          console.log(res.status)
        })
      }
      location.reload()
    },
    onDle (id) {
      axios({
        url: 'books/' + id,
        method: 'DELETE'
      }).then((res) => {
        console.log(res.status)
      })
      location.reload()
    },
    revise (id) {
      axios({
        url: 'books/' + id,
        method: 'GET'
      }).then((res) => {
        this.newName = res.data.name
        this.newId = id
      })
    }
  },
  filters: {
    newdate (val) {
      const date = new Date(val)
      var y = date.getFullYear()
      var mou = date.getMonth() + 1
      var d = date.getDate()
      var h = date.getHours()
      var m = date.getMinutes()
      var s = date.getSeconds()
      return y + '-' + mou + '-' + d + ' ' + h + ':' + m + ':' + s
    }
  }
}
</script>

<style scoped lang="less"></style>
